<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../layui/css/layui.css" media="all">
<title>分店批发</title>
</head>
<style>
#addWholesale{
    	position:absolute;
    	top:0%;
    	z-index: 200;
    	background: rgb(0,0,0,0.9);
    	width:100%;
    	height: 200%;
    	display: none;
}
#showPch{
    	position: absolute;
    	left: 35%;
    	top: 28%;
    	width: 30%;
    	background: white;
    	
}
#submits{
	position: fixed;
	top:7%;
	left: 84%;
}
#cancel{
	position: fixed;
	top:7%;
	left: 90%;
}
</style>
<body>

	<fieldset class="layui-elem-field layui-field-title"
		style="margin-top: 20px;">
		<legend>批发药品及数量</legend>
	</fieldset>
	
	<div class="layui-inline">
		<table class="layui-table" id="fdpf"  >
			<colgroup>
		      <col width="150">
		      <col width="120">
		      <col width="150">
		      <col width="120">
		      <col width="120">
		      <col width="100">
		      <col width="100">
		    </colgroup>
		    <thead>
				<tr>
			  		<th>药品名称</th>
			  		<th>批次号</th>
			  		<th>药品单位</th>
			  		<th>建议零售价</th>
			  		<th>批发价</th>
			  		<th>批发数量</th>
			  		<th>小计</th>
			  		<th>操作</th>
			  	</tr>
		  	</thead>
		  	<tfoot  >
		  		<tr >
			  		<td></td>
			  		<td></td>
			  		<td></td>
			  		<td></td>
			  		<td style="font-size: 23px">总数：</td>
			  		<td id="sum"></td>
			  		<td style="font-size: 23px">合计：</td>
			  		<td id="total"></td>
			  	</tr>
		  	</tfoot>
		</table>
		<button class="layui-btn" data-type="submits" id="submits" style="z-index: 100">提交</button>
		<button class="layui-btn" data-type="cancel"  id="cancel" style="z-index: 100">取消</button>
	</div>
	<P>&nbsp;</P>
	<P>&nbsp;</P>
	<div class="demoTable">
		  搜索:
		  <div class="layui-inline">
		    <input class="layui-input" name="drugName" id="drugName" autocomplete="off" placeholder="输入药品关键字">
		  </div>
		  <button class="layui-btn" data-type="reload">搜索</button>
	</div>
	<table class="layui-hide" id="DrugModel" lay-filter="demo"></table>
	<div id="addWholesale">
		<div id="showPch">
			<fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
			  <legend>药品批次及数量选择</legend>
			</fieldset>
			<form class="layui-form" id="addForms" onsubmit="return false" method="post" >
			
			  <div class="layui-form-item">
			    <label class="layui-form-label">药品名称</label>
			    <div class="layui-input-block">
			      <input type="hidden" name="pwId" id="pwIds">
			      <input type="text" name="drugName" id="drugNames" disabled="disabled" maxlength="20" lay-verify="required"  autocomplete="off" class="layui-input" style="width:150px;">
			    </div>
			  </div>
			  <div class="layui-form-item">
			    <label class="layui-form-label">药品批次号</label>
			    <div class="layui-input-block" style="width:150px;">
			      <select name="numbers" id="numbers" lay-filter="numbers" lay-verify="required" lay-search="">
			          
			       </select>
			    </div>
			  </div>
			  <div class="layui-form-item layui-form-text">
			    <label class="layui-form-label" >该批次库存数量</label>
			    <div class="layui-input-block">
			      <input placeholder="库存数量" disabled="disabled" maxlength="18" name="kcNumber" id="kcNumber" class="layui-input"  style="width:150px;"/>
			    </div>
			  </div>
			  <div class="layui-form-item layui-form-text">
			    <label class="layui-form-label" >批发数量</label>
			    <div class="layui-input-block">
			      <input placeholder="数量" onkeyup="this.value=this.value.replace(/[^\d]/g,'') " onafterpaste="this.value=this.value.replace(/[^\d]/g,'') " maxlength="20" name="numbersa" id="cgNumber" class="layui-input" lay-verify="required" style="width:150px;" />
			    </div>
			  </div>
			  <div class="layui-form-item">
			    <div class="layui-input-block">
			      <input type="submit" id="addWhole" class="layui-btn " lay-submit="addWhole" lay-filter="addWhole" value="提交">
			      <button id="closeAdd" type="reset" class="layui-btn layui-btn-primary" >取消</button>
			    </div>
			  </div>
		 </form>
		</div>
	</div>
 <script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-xs " lay-event="edit" id="imgUpdate">加入批发单</a>
</script>

<script type="text/javascript" src="../../res/js/base.js"></script>
<script src="../../layui/layui.js"></script>
<script type="text/javascript" src="../../js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="../../res/mln/getUrlParam.js"></script>
<script>
var path=getRootPath();
//取到销售ID
var pfId = getUrlParam('pfId');
//取到批发的总数量和金额
var sumNumber=getUrlParam('sum');
var totalSum=getUrlParam('total');

layui.use(['form','laydate', 'laypage', 'layer', 'table', 'upload', 'element'], function(){
	  var laydate = layui.laydate //日期
	  ,laypage = layui.laypage //分页
	  ,layer = layui.layer //弹层
	  ,table = layui.table //表格
	  ,upload = layui.upload //上传
	  ,element = layui.element //元素操作
	 ,form = layui.form;
	  
	  //监听Tab切换
	  element.on('tab(demo)', function(data){
	    layer.msg('切换了：'+ this.innerHTML);
	    console.log(data);
	  });
	  
	  //执行一个 table 实例
	  table.render({
	     elem: '#DrugModel'
	    ,cellMinWidth: 80
	    ,url: getRootPath()+'DrugModel/findAll.action' //数据接口
	    ,page: true //开启分页
	    ,method:'post'
	    ,cols: [[ //表头
	       {field: 'dtName', title: '药品类型', width:200}
	      ,{field: 'drugBarCode', title: '药品编码', width:200}
	      ,{field: 'drugName', title: '药品名称', width:200}
	      ,{field: 'drugPrice', title: '药品价格', width:100}
	      ,{field: 'pov', title: '药品单位', width:100}
	      ,{field: 'drugPrices', title: '建议零售价', width:100}
	      ,{field: 'drugPinyin', title: '药品拼音简称', width:200}
	      ,{field: 'drugImg',title:'药品图片', width:120, templet:'<div><img src="{{ d.drugImg}}"></div>'}
	      ,{fixed: 'right',title: '操作', width: 100, align:'center', toolbar: '#barDemo'}
	    ]]
	  	,id: 'testReload'
	  });
	  
	  var $ = layui.$;
	  //监听工具条
	  table.on('tool(demo)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
	    var data = obj.data //获得当前行数据
	    ,layEvent = obj.event; //获得 lay-event 对应的值
	    if(layEvent === 'edit'){
	      var drugId=data.drugId;
	      var data={drugId:drugId}
	      $("#pwIds").val(drugId);
	      var url=path+"Inventory/findByfilId.action";
	      $.post(url,data,function(data){
	    	  
	    	  if(data==null||data==""){
	    		  layer.msg('亲，库存不够了', {
					  icon: 5,
					  time: 1000 //1秒关闭（如果不配置，默认是3秒）
					}, function(){
					  
				});
	    	  }else{
	    		  
	    		  
	    		  $("#drugNames").val(data[0].itemName);
	    		  $("#numbers").html('<option value="">请选择批次号</option>');
	    		  for(var i=0;i<data.length;i++){
	    			  $("#numbers").append("<option value='"+data[i].invNumber+"' >"+data[i].numbers+"</option>");
	    		  }
	    		  layui.form.render();
	    		  $('#addWholesale').css('display', 'block');
	    	  }
	      });
	    } 
	  });
	  
	 
	  //条件查询	  
	  $('.demoTable .layui-btn').on('click', function(){
		 var drugName = $('#drugName');
		 //执行重载
	     table.reload('testReload', {
	       page: {
	         curr: 1 //重新从第 1 页开始
	       }
	       ,where: {
	    	   drugName: drugName.val()
	       }
	     });
	  });
	  $('#closeAdd').on('click', function() {
			$('#addWholesale').css('display', 'none');
		});
	  
	  form.on('select(numbers)', function(data){
		  
		  var oCar = document.getElementById("fdpf");
		  var tr=oCar.getElementsByClassName("iii");
		  var trs=oCar.getElementsByClassName("pfxqNum");
		  var pc=oCar.getElementsByClassName("pcNumber");
		  
		  //得到tr的长度
		  var len = tr.length;
		  var ai=data.value;
		  
		  var obj=document.getElementById("numbers");
	      for(i=0;i<obj.length;i++){
	         if(obj[i].selected==true){
	        	 var numbers=obj[i].innerText;//关键是通过option对象的innerText属性获取到选项文本
	         }
	      }
		  //for 循环id为goods表格的数据
		  for(i=0;i<len;i++){
			  //得到点击选中药品的名字
			  var sj=tr[i].innerHTML;
			  var pcs=pc[i].innerHTML;
			  //得到表格id为goods药品的名字
			  var joo=$("#drugNames").val();
			  
			  //判断当选中药品的名字和goods表格中药品名字为一致时
			  if(sj==joo&&pcs==numbers){
				  ai=parseInt(data.value)-parseInt(trs[i].innerHTML);
				  //跳出循环 
				  break;
			  }
		  }
		  $("#kcNumber").val(ai);
		  
		  form.render();
		});
	  
	  $("#cgNumber").on('input propertychange',function(){
		  var nums=parseInt($("#cgNumber").val());
		  if($("#kcNumber").val()==""){
			  var num=0;
		  }else{
			  var num=parseInt($("#kcNumber").val());
		  }
		  if(num<nums||num==0){
			  nums=num
			  layer.msg('亲，库存不够了', {
				  icon: 5,
				  time: 1000 //1秒关闭（如果不配置，默认是3秒）
				}, function(){
				  
			});
	  	  }
	  	$("#cgNumber").val(nums);
	  	
	  });
	  $("#submits").on('click',function(){
			//设置一个数组
		    var arr = [];
			//设置一个数
			var number=0;
		    //得到goods表格的数据
			 $("#fdpf tr").each(function(){
				 if(number>1){
					 var row = "";
					 var td = $(this).find("td");
					 row={"drugName":$(td[0]).text(),"numbers":$(td[1]).text(),"pfxqUnit":$(td[2]).text(),"drugPrice":$(td[3]).text(),"pfxqPrice":$(td[4]).text(),"pfxqNumber":$(td[5]).text(),"pfxqSubtotal":$(td[6]).text(),"pwId":$(td[7]).text()};
					 //将数据加入进去
					 arr.push(row);
				 }
				 number=number+1;
			 });
		  	 //转换json数据
			 var arrs = JSON.stringify(arr);
		  	 var sum=$("#sum").html();
		  	 var totals=$("#total").html();
		  	 
		  	 if(arrs=="[]"){
		  		layer.msg('亲，请选择药品后再提交', {
					  icon: 5,
					  time: 1500 //1秒关闭（如果不配置，默认是3秒）
					}, function(){
					  
				});
		  	 }else{
		  		//通过ajax方式传入到后台
				 $.ajax({
	                 url:"../../wholesaleDetail/updates.action",
	                 data:{arr:arrs,sum:sum,totals:totals,pfId:pfId},
	                 type: "post",
	                 dataType:"json",
	                 cache:false,
	                 async: false,
	                 success: function(obj){
	                	 alert(obj);
	                	
	                 }
	              });
				 //刷父新页面
				 parent.location.reload();
		  	 }
	  });
	  $("#cancel").on('click',function(){
		  parent.location.reload();
	  });
	  form.on('submit(addWhole)',function(data){
		  
		  var obj=document.getElementById("numbers");
	      for(i=0;i<obj.length;i++){
	         if(obj[i].selected==true){
	        	 var numbers=obj[i].innerText;//关键是通过option对象的innerText属性获取到选项文本
	         }
	      }
		  var pwId=$("#pwIds").val();
		  var invNumber=$("#cgNumber").val();
		  var data={numbers:numbers,pwId:pwId,invNumber:invNumber};
		  
		  
		  var url=path+"wholesaleDetail/storage.action";
		  
		  $.post(url,data,function(msg){
			  
			  if(msg==null||msg==""){
				  layer.msg('亲，该批次号信息出问题了，暂时不能购买', {
					  icon: 5,
					  time: 1000 //1秒关闭（如果不配置，默认是3秒）
					}, function(){
					  
				});
			  }else{
				  var oCar = document.getElementById("fdpf");
				  
				  var tr=oCar.getElementsByClassName("iii");
				  var tra=oCar.getElementsByClassName("pfxqShub");
				  var trs=oCar.getElementsByClassName("pfxqNum");
				  //得到tr的长度
				  var len = tr.length;
				  var ai=0;
				  //总数量
				  var nums=0;
				  //合计
				  var total=0;
				  //for 循环id为goods表格的数据
				  for(i=0;i<len;i++){
					  //得到点击选中药品的名字
					  var sj=tr[i].innerHTML;
					  //得到表格id为goods药品的名字
					  var joo=msg.drugName;
					  
					  //判断当选中药品的名字和goods表格中药品名字为一致时
					  if(sj==joo){
						  ai=1;
						  tra[i].innerHTML=parseInt(msg.pfxqSubtotal)+parseInt(tra[i].innerHTML);
						  trs[i].innerHTML=parseInt(msg.pfxqNumber)+parseInt(trs[i].innerHTML);
						  
						  nums=nums+parseInt(trs[i].innerHTML);
						  
						  total=total+parseInt(tra[i].innerHTML);
					  }else{
						  nums=nums+parseInt(trs[i].innerHTML);
						  total=total+parseInt(tra[i].innerHTML);
					  }
				  }
				  
				  if(ai==0){
					  $("#fdpf").append('<tr><td class="iii">'+msg.drugName+'</td><td class="pcNumber">'+msg.numbers+'</td><td>'+msg.pfxqUnit+'</td><td>'+msg.drugPrice+'</td><td>'+msg.pfxqPrice+'</td><td class="pfxqNum">'+msg.pfxqNumber+'</td><td class="pfxqShub">'+msg.pfxqSubtotal+'</td><td style="display:none">'+msg.pwId+'</td><td><a href="javascript:;" onclick="show(this)">删除</a></td></tr>');
					  nums=parseInt(msg.pfxqNumber);
					  
					  total=parseInt(msg.pfxqSubtotal);
				  }
				  $("#sum").html(nums);
				  $("#total").html(total);
				  $('#addWholesale').css('display', 'none');
				  $("#pwIds").val("");
				  $("#cgNumber").val("");
				  $("#kcNumber").val("");
				  $("#drugNames").val("");
			  
			  }
		  });
		  
		  
	  });
	
	});
function show(obj){
	var oDivs= obj.parentNode.parentNode;
	var nums=parseInt($("#sum").html())-parseInt(oDivs.childNodes[5].innerHTML);
	var total=parseInt($("#total").html())-parseInt(oDivs.childNodes[6].innerHTML);
	$("#sum").html(nums);
	$("#total").html(total);
	obj.parentNode.parentNode.parentNode.removeChild(oDivs);
	
}
load();
function load(){
	$("#sum").html(sumNumber);
	$("#total").html(totalSum);
	var url=path+'wholesaleDetail/wholesaleDetailFindAll.action';
	var data={pfId:pfId};
	$.post(url,data,function(msg){
		for(var i=0;i<msg.length;i++){
			 $("#fdpf").append('<tr><td class="iii">'+msg[i].drugName+'</td><td class="pcNumber">'+msg[i].numbers+'</td><td>'+msg[i].pfxqUnit+'</td><td>'+msg[i].drugPrice+'</td><td>'+msg[i].pfxqPrice+'</td><td class="pfxqNum">'+msg[i].pfxqNumber+'</td><td class="pfxqShub">'+msg[i].pfxqSubtotal+'</td><td style="display:none">'+msg[i].pwId+'</td><td><a href="javascript:;" onclick="show(this)">删除</a></td></tr>');
		}
	});
}
</script>
</body>
</html>